package com.barbeque.mall.aspect;

import com.barbeque.mall.exception.ValidationException;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * 参数校验
 *
 * @author Euphonium
 * @since 2022/07/18
 */
@Aspect
@Component
public class ParamValidationAspect {

    @Pointcut("@annotation(com.barbeque.mall.anno.ParamValidation)")
    public void validatePointcut() {
    }

    @Before("validatePointcut() && args(.., bindingResult)")
    public void paramValidate(BindingResult bindingResult) throws ValidationException {
        if (bindingResult.hasErrors()) {
            // 成员变量中存在校验错误
            FieldError fieldError = bindingResult.getFieldError();
            // 校验错误的请求参数
            String field = fieldError.getField();
            // 错误信息
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + defaultMessage;
            throw new ValidationException(msg);
        }
    }

}
